package com.gateway.filter;

import com.itheima.common.util.AppJwtUtil;
import com.itheima.common.util.SystemConstants;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * @Author: lqj
 * @Date: 2022/11/16/15:57
 * @Description:
 */
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //先获取请求和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();

        String path = request.getURI().getPath();
        if (path.startsWith("/api/log/land")) {
            return chain.filter(exchange);
        }

        //获取页面传递过来的请求头中的令牌数据 如果获取不到 返回错误（401）
        String token = request.getHeaders().getFirst("token");
        if (StringUtils.isEmpty(token)) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //完成响应 返回 后面就不执行了
            return response.setComplete();
        }
        //校验令牌 校验失败 返回错误401
        //通过jwt 来校验
        if (!SystemConstants.JWT_OK.equals(AppJwtUtil.verifyToken(token))) {
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            //完成响应 返回 后面就不执行了
            return response.setComplete();
        }
        //校验成功 放行
        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
